package com.atguigu.tingshu.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.account.client.RechargeInfoFeignClient;
import com.atguigu.tingshu.common.Assert;
import com.atguigu.tingshu.common.constant.RabbitConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderInfoFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @author sun
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Resource
    private PaymentInfoMapper paymentInfoMapper;
    @Resource
    private OrderInfoFeignClient orderInfoFeignClient;
    @Resource
    private RechargeInfoFeignClient rechargeInfoFeignClient;
    @Resource
    private RabbitTemplate rabbitTemplate;


    /**
     * 保存交易记录
     *
     * @param type    支付类型 1301-订单 1302-充值
     * @param orderNo 订单号
     * @return PaymentInfo交易记录信息
     */
    @Override
    public PaymentInfo savePaymentInfo(String type, String orderNo) {

        // 获取交易记录对象
        // TODO 这里只会有一个交易记录吗，换了支付方式，但是没有删除原来的会不会产生额外的交易记录？？？
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderNo));
        // 保证微信支付只插入一个交易记录
        if (paymentInfo == null) {
            // 创建交易记录
            paymentInfo = new PaymentInfo();
            paymentInfo.setPaymentType(type);
            paymentInfo.setOrderNo(orderNo);
            paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
            if(type.equals(SystemConstant.PAYMENT_TYPE_ORDER)){
                Result<OrderInfo> orderInfoResult = orderInfoFeignClient.getOrderInfo(orderNo);
                Assert.notNull(orderInfoResult, ResultCodeEnum.ORDER_INFO_REMOTE_CALL_ERROR);
                OrderInfo orderInfo = orderInfoResult.getData();
                paymentInfo.setUserId(orderInfo.getUserId());
                paymentInfo.setContent(orderInfo.getOrderTitle());
                paymentInfo.setAmount(orderInfo.getOrderAmount());
            }else{
                // 充值
                Result<RechargeInfo> rechargeInfoResult = rechargeInfoFeignClient.getRechargeInfo(orderNo);
                Assert.notNull(rechargeInfoResult, ResultCodeEnum.RECHARGE_INFO_REMOTE_CALL_ERROR);
                RechargeInfo rechargeInfo = rechargeInfoResult.getData();
                paymentInfo.setUserId(rechargeInfo.getUserId());
                paymentInfo.setContent(SystemConstant.RECHARGE_CONTENT);
                paymentInfo.setAmount(rechargeInfo.getRechargeAmount());
            }
            paymentInfoMapper.insert(paymentInfo);
        }
        return paymentInfo;
    }

    /**
     * 更新交易记录
     *
     * @param transaction 交易记录
     */
    @Override
    public void updatePaymentStatus(Transaction transaction) {

        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, transaction.getOutTradeNo()));
        if(Objects.equals(paymentInfo.getPaymentStatus(), SystemConstant.PAYMENT_STATUS_PAID)){
            return;
        }

        // 更新交易记录
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
        paymentInfo.setOutTradeNo(transaction.getTransactionId());
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(JSONObject.toJSONString(transaction));
        paymentInfoMapper.updateById(paymentInfo);

        // 更新订单状态  使用消息队列
        rabbitTemplate.convertAndSend(RabbitConstant.ORDER_EXCHANGE, RabbitConstant.ORDER_SUCCESS_KEY, paymentInfo.getOrderNo());

    }
}
